package com.kakame.pastime.common.utils.fastdfs;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.jfinal.aop.Duang;
import com.jfinal.upload.UploadFile;
import com.kakame.pastime.common.init.FastdfsConfig;
import com.kakame.pastime.common.service.AttachService;
import com.kakame.pastime.common.utils.fastdfs.base.StorePath;
import com.kakame.pastime.common.utils.fastdfs.main.StorageClient;
import com.kakame.pastime.common.utils.fastdfs.main.StorageServer;
import com.kakame.pastime.common.utils.fastdfs.main.TrackerClient;
import com.kakame.pastime.common.utils.fastdfs.main.TrackerServer;

public class FastdfsUtil {
	
	public static FastdfsUtil me = new FastdfsUtil();
	
	private AttachService fileService = Duang.duang(AttachService.class);
	
	/**
	 * 上传单个文件，并返回具体属性
	 * @auth 何家明
	 * @date 2018年11月23日 下午3:31:37
	 * @param filePath
	 * @return
	 */
	public StorePath uploadSingleFile(String filePath) {
		TrackerClient tracker = new TrackerClient(); 
		TrackerServer trackerServer = tracker.getConnection();
		StorageServer storageServer = null;
		StorageClient storageClient = new StorageClient(trackerServer, storageServer); 
		
		String fileExtName = filePath.substring(filePath.lastIndexOf(".") + 1);
		
		String storePath[] = storageClient.upload_file(filePath, fileExtName, null);
		
		StorePath f = new StorePath();
		f.setGroup(storePath[0]);
		f.setPath(storePath[1]);
		
		fileService.insert(f);
		
		return f;
	}
	
	/**
	 * 上传多个文件后直接返回下载路径
	 * @auth 何家明
	 * @date 2018年11月23日 下午3:32:35
	 * @param files
	 * @return
	 */
	public static List<String> uploadMutilFilesReturnUrls(List<UploadFile> files) {
		List<String> urls = new ArrayList<String>();
		for (UploadFile file : files) {
			// StorePath [group=group1, path=M00/00/00/rBJtj1tKFQSACoRxAAmFdbR27oc188.jpg]
			StorePath storePath = FastdfsUtil.me.uploadSingleFile(file.getUploadPath() + File.separator + file.getOriginalFileName());
			String url = FastdfsConfig.file_download_address + "/" + storePath.getGroup() + "/" + storePath.getPath();
			urls.add(url);
		}
		return urls;
	}
}
